﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using ECommerce.Model.Product;

namespace ECommerce.Web.Site
{
    public partial class PutCart : System.Web.UI.Page
    {
        private string ProductID
        {
            get
            {
                return Request.QueryString["ProductID"];
            }
        }

        private string ProductCount
        {
            get
            {
                return Request.QueryString["ProductCount"];
            }
        }

        private string ProductSize
        {
            get
            {
                return Request.QueryString["ProductSize"];
            }
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            string shoppingCart = null;
            if (Request.Cookies["ShoppingCart"] != null)
            {
                shoppingCart = Request.Cookies["ShoppingCart"].Value;
            }
            if (string.IsNullOrEmpty(shoppingCart))
            {
                shoppingCart = ProductID + "_" + ProductCount + "_" +  Server.UrlEncode(ProductSize);
            }
            else
            {
                string[] idCounts = shoppingCart.Split(',');

                List<ECProductInfo> tmpInfos = new List<ECProductInfo>();
                foreach (string idcount in idCounts)
                {
                    ECProductInfo info = new ECProductInfo();
                    info.ID = int.Parse(idcount.Split('_')[0]);
                    info.BuyCount = int.Parse(idcount.Split('_')[1]);
                    info.Size = Server.UrlDecode(idcount.Split('_')[2]);
                    tmpInfos.Add(info);
                }

                if (tmpInfos.Exists(T => T.ID == int.Parse(ProductID)))
                {
                    tmpInfos.Where(T => T.ID.ToString() == ProductID).First().BuyCount += int.Parse(this.ProductCount);
                }
                else
                {
                    ECProductInfo info = new ECProductInfo();
                    info.ID = int.Parse(this.ProductID);
                    info.BuyCount = int.Parse(this.ProductCount);
                    info.Size = this.ProductSize;
                    tmpInfos.Add(info);
                }

                shoppingCart = "";
                foreach (ECProductInfo info in tmpInfos)
                {
                    shoppingCart += info.ID + "_" + info.BuyCount + "_" + Server.UrlEncode(info.Size) + ",";
                }
                shoppingCart = shoppingCart.TrimEnd(',');


            }
            HttpCookie cookie = new HttpCookie("ShoppingCart", shoppingCart);
            cookie.Expires = DateTime.Now.AddHours(12);
            Response.Cookies.Add(cookie);

            Response.Redirect("Shopping1.aspx");
        }
    }
}